(function(window,undefined){
	var Coupon = {};
	window.Coupon = window.Coupon || Coupon;
	/* side-menu > 인기쿠폰 index.php,index_log.php*/
	
	var loadRecommendCoupon = function(successCallback){
		var strLandmark = sessionStorage.getItem('landmark_code');
		var strParentLM = strLandmark.substring(0,2);
		var strCategory = sessionStorage.getItem('category_code');
		
		$.ajax({
			type:'post',
			url:ajaxURL+'coupon.php?action=loadRecommendCoupon',
			data:{
				parent_landmark:strParentLM,
				category_code:strCategory
			},
			dataType:'json',
			success:function(result){
				successCallback(result);
			}
		});
	};
	
	Coupon.couponPage = {
		recommendCouponBlock : function(){
			/*model connect*/
			loadRecommendCoupon(function(result){
				console.log(result);
				var selector = '#x_recommend_coupon'; /*recommend*/
				template.couponList(result,selector);
				
			});
		}
	};
	
	Coupon.popularCouponBlock = function(){
		var _row=0;
		popularCouponBlock(_row);
		$('.widgetPagination:nth(0) a:nth(0)').on("click",function(event){
			event.preventDefault();
			_row =0;
			$('.widgetPagination:nth(0) a').removeClass('on');
			$(this).addClass('on');
			popularCouponBlock(_row);
			
		});
		$('.widgetPagination:nth(0) a:nth(1)').on("click",function(event){
			event.preventDefault();
			_row =4;
			$('.widgetPagination:nth(0) a').removeClass('on');
			$(this).addClass('on');
			popularCouponBlock(_row);
			
		});
	};
	
	var popularCouponBlock = function(_row){
		var selector = 'ul.couponListWidget';
		var _landmark_code = sessionStorage.getItem('landmark_code');
		var _category= sessionStorage.getItem('category_code');
		if(_landmark_code == null){
			_landmark_code = 'GGSNMR';
		}
		
		if(!_category){
			_category = DEFAULT_CATEGORY;
		}
		
		
		$.ajax({
			type:"post",
			url:ajaxURL + "coupon.php?action=loadPopularCouponList",
			dataType:"json",
			data:{row:_row},
			success:function(result){
				console.log('popularCouponBlock');
				console.log(result.data);
				$(selector).empty();
	
				if(result.dataLength == 0){
				//	$('div.right section:nth(0)').empty();
					template.noSideCoupon(selector);
					$('.widgetNoneWrap').css("border","none");
					//$('.unitWrap.styleA li').css('padding','0');
				}
				if(result.dataLength<=4){
					$('ul.widgetPagination:nth(0)').remove(); 
				}
				
				$.each(result.data,function(key){
					if(!this.image || this.image == null || this.image == ''){
						this.image = "images/default_store.png";
					}
					// this.image.onerror =function (evt){
						// this.image = "images/default_store.png";
					// }
										/*첫번째 리스트 구분*/
					if(key==0){
						key= 'class="first-child"';	
					}
					
					template.sideCouponList(this,selector,key,'popular');
				});
				
				
			}
		});
		
		
	};
	Coupon.couponPrintBlock=function(){
		var _coupon_id=getUrlId();
		$('.buttonWrap a:nth(0) img').on("click",function(event){
            event.preventDefault();
            window.print(confirm);
        });
        $('.buttonWrap a:nth(1) img').on("click",function(event){
       		window.close();
        });
        
        $.ajax({
			type:"post",
			url:ajaxURL + "coupon.php?action=loadPrintCouponInfo",
			dataType:"json",
			data:{coupon_id:_coupon_id},
			success:function(result){
				console.log("loadPrintCouponInfo");
				console.log(result[0]);
				var time= new Date(result[0].created_date);
				var _coupon_srl=_coupon_id+time.getTime()/1000+sessionStorage.getItem('user_id');
				if(result[0].addr0==null){result[0].addr0=''}
				else if(result[0].addr1==null){result[0].addr1=''}
				else if(result[0].addr2==null){result[0].addr2=''}
				else if(result[0].addr3==null){result[0].addr3=''}
				else if(result[0].addr4==null){result[0].addr4=''}
				$('ul.couponList h4.title').html(result[0].coupon_title);
				$('ul.couponList div.store a').html(result[0].store_name);
				$('ul.couponList div.tags').html('랜드마크 : '+result[0].landmark_name);
				$('ul.couponList div.date').html(result[0].expired_date.split(" ")[0] +" 까지 사용가능");
				$('ul.couponList div.thumbWrap img').attr('src',result[0].image);
				$('ul.couponList div.thumbWrap img').css({'width':'160px','height':'120px'});
				$('section h2').html(result[0].store_name);
				$('section div.couponNumber b').html(_coupon_srl);
				$('table td:nth(0)').html(result[0].addr0+' '+result[0].addr1+' '+result[0].addr2+' '+result[0].addr3+' '+result[0].addr4);
				$('table td:nth(1)').html(result[0].telephone);
				$('table td:nth(2)').html(result[0].coupon_description);
			}
		});
	};
	
	var couponListener = function(){
		/*쿠폰 다운*/
		$('.downWrap a,.downCount a').off('click').on('click', function(event) {
				
			event.preventDefault();
			var _coupon_id=$(this).data('coupon_id');
		
			if(Account.isLogin()==true){
				addPouch(_coupon_id);
				$(this).children().attr('src','images/btn_coupon_s_ok.png');
			}else{
				alert(NEED_LOGIN_MESSAGE);
				location.href="login.php";
			}
		});
		

		$('.cnt span').off('click').on('click', function(event) {
			//$(this).parents().find('li').printArea();
			//$(this).parent().parent().parent().printArea();
			// w=window.open();
			// w.document.write('<ul style="display: block;clear: both;width: 100%;"><li style="padding: 14px;display: block;border: 1px solid #ccc;position: relative;background: #fff;float: none;margin: 0 0 10px 0;">'+$(this).parent().parent().parent().html()+'</li></ul>');
			// w.print();
			// w.close();
			event.preventDefault();
			var _coupon_id=$(this).data('coupon_id');
			window.open('mycoupon_print.php?id='+_coupon_id,'_blank',"width=800, height=600, toolbar=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no" );
			
		});

		
		
		

		function printElem(options,that){   
		//that="<ul class='couponList unitWrap styleB'>"+that+"</ul>";
		that.parent().parent().parent().printElement(options); //팝업으로 띄울 영역 Div 아이디
		//$('#print').printElement(options);
		}
		/*쿠폰 공유하기*/
	};
	Coupon.StoreCouponListBlock = function(){
		var _row=0;
		storeCouponList(_row);
		$('.widgetPagination a:nth(0)').on("click",function(event){
			event.preventDefault();
			_row =0;
			$('.widgetPagination a').removeClass('on');
			$(this).addClass('on');
			storeCouponList(_row);
			
		});
		$('.widgetPagination a:nth(1)').on("click",function(event){
			event.preventDefault();
			_row =3;
			$('.widgetPagination a').removeClass('on');
			$(this).addClass('on');
			storeCouponList(_row);
			
		});
		
		
	};
	
	var storeCouponList = function(_row){
		var selector = 'ul.couponListWidget';
		var _store_id = getUrlId();
		var _user_id = sessionStorage.getItem('user_id');
		$.ajax({
			type:"post",
			url:ajaxURL + "coupon.php?action=loadStoreCouponList",
			dataType:"json",
			data:{store_id:_store_id,user_id:_user_id,row:_row},
			success:function(result){
				console.log("StoreCouponListBlock");
				console.log(result);
				$(selector).empty();
	
				if(result.dataLength == 0){
					template.noSideCoupon(selector);
					$('div.widgetNoneWrap').css("border","none");
					//$('.unitWrap.styleA li').css('padding','0');
					
				}
				if(result.dataLength<=3){
					$('ul.widgetPagination').remove();
				}
				
				$.each(result.data,function(key){
					if(this.image == null || this.image == ''){
						this.image = "images/default_store.png";
					}
					
					/*첫번째 리스트 구분*/
					if(key==0){
						key= 'class="first-child"';	
					}
					
					template.sideCouponList(this,selector,key,'store');
				});
				couponListener();
			}
		});
	}
	/* coupon.php > 쿠폰 리스트*/
	Coupon.couponList = function(){
		var selector = 'ul.couponList';
		var _landmark_code = sessionStorage.getItem('landmark_code');
		var _category= sessionStorage.getItem('category_code');
		
		if(_landmark_code == null){
			_landmark_code = 'SGSBMR';
		}
		if(!_category){
			_category = DEFAULT_CATEGORY;
		}
		
		$.ajax({
			type:"post",
			url:ajaxURL + "coupon.php?action=loadCouponList",
			dataType:"json",
			data:{category:_category,landmark_code:_landmark_code,row:Paging.getCurrent(),to:10},
			success:function(result){
				console.log("loadCouponList");
				console.log(result.data);
				$(selector).empty();
	
				if(result.dataLength == 0){
					
					template.noCoupon(selector);
				}
				
				$.each(result.data,function(){
					if(this.image == null || this.image == ''){
						this.image = "http://buzzbee.kr/s.oh/guppii_ver1/guppiiweb_ver1/images/default_store.png";
					}
					if(this.expired_date == null){
						this.expired_date = "무제한";
					}else {
						var temp = this.expired_date.split(' ');
						temp = temp[0].split('-');
						this.expired_date = temp[1] + '월 ' + temp[2] +'일까지';
					}
					
					
											
					template.couponList(this,selector);
					//__callback(this);
				});
				
				$('span.headCount > b:nth(0)').html(result.dataLength);
				/*MY리스트-쿠폰공유*/
				$('#fbShareBtn').off('click').on('click',function(){
					var coupon_obj = {};
					coupon_obj.store_id=$('#fbShareBtn').attr('store_id'),
					coupon_obj.store_name=$('#fbShareBtn').attr('store_name'),
					coupon_obj.coupon_title=$('#fbShareBtn').attr('coupon_title'),
					coupon_obj.coupon_desc=$('#fbShareBtn').attr('coupon_desc'),
					coupon_obj.coupon_img=$('#fbShareBtn').attr('coupon_img');
					Sns.couponShareToFacebook(coupon_obj);
				});
				couponListener();
				var _para = {
					dataLength : result.dataLength,
					// dataLength : 1000,
					selector : '#pagination > ul',
					callback : function(){
						Coupon.couponList();
					}
				};
				
				Paging.innerAJAX(_para);
			}
		});
	};
	
	/*쿠폰북 mycoupon.php*/
	Coupon.myCouponBlock = function(){
		myCouponList();
		$('#sorting1').off('click').on("click",function(event){
			event.preventDefault();
			Paging.initCurrentPage();
			myCouponList('최신순');
			$(this).addClass('orange');
			$('#sorting2,#sorting3').removeClass('orange');
		});
		
		$('#sorting2').off('click').on("click",function(event){
			event.preventDefault();
			Paging.initCurrentPage();
			myCouponList('마감순');
			$(this).addClass('orange');
			$('#sorting1,#sorting3').removeClass('orange');
		});
		
		$('#sorting3').off('click').on("click",function(event){
			event.preventDefault();
			Paging.initCurrentPage();
			myCouponList('거리순');
			$(this).addClass('orange');
			$('#sorting1,#sorting2').removeClass('orange');
		});
	};
	
	var myCouponList = function(_sorting){
		var selector = 'ul.couponList';
		var _landmark_code = sessionStorage.getItem('landmark_code');
		if(_landmark_code == null){
			_landmark_code = 'SGSBMR';
		}
		var _user_id = sessionStorage.getItem('user_id');
		
		if(!_sorting){
			_sorting = '최신순';
		}
		
		$.ajax({
			type:"post",
			url:ajaxURL + "coupon.php?action=loadMyCouponList",
			dataType:"json",
			data:{user_id:_user_id,landmark_code:_landmark_code,sorting : _sorting,row:Paging.getCurrent()},
			success:function(result){
				console.log('myCouponList');
				console.log(result);
				$(selector).empty();
	
				if(result.dataLength == 0){
					
					template.noMyCoupon(selector);
				}
				
				$.each(result.data,function(){
					if(this.image == null || this.image == ''){
						this.image = "http://buzzbee.kr/s.oh/guppii_ver1/guppiiweb_ver1/images/default_store.png";
					}
					if(this.expired_date == null){
						this.expired_date = "무제한";
					}else {
						var temp = this.expired_date.split(' ');
						temp = temp[0].split('-');
						this.expired_date = temp[1] + '월 ' + temp[2] +'일까지';
					}
					template.myCouponList(this,selector);	
					
					
				});
				/*쿠폰리스트-쿠폰공유*/				
				$('#fbShareBtn').off('click').on('click',function(){
					var coupon_obj = {};
					coupon_obj.store_id=$('#fbShareBtn').attr('store_id'),
					coupon_obj.store_name=$('#fbShareBtn').attr('store_name'),
					coupon_obj.coupon_title=$('#fbShareBtn').attr('coupon_title'),
					coupon_obj.coupon_desc=$('#fbShareBtn').attr('coupon_desc'),
					coupon_obj.coupon_img=$('#fbShareBtn').attr('coupon_img');
					Sns.couponShareToFacebook(coupon_obj);
				});
				$('div.countWrap').html('(<b>'+result.dataLength+'</b>개)');
				couponListener();
				var _para = {
					dataLength : result.dataLength,
					// dataLength : 1000,
					selector : '#pagination > ul',
					callback : function(){
						var selectSorting=$('ul.headFilter a.orange').html();
						myCouponList(selectSorting); 
						
					}
				};
				
				Paging.innerAJAX(_para);
			}
		});
		
		
	};
	
	
	/* coupon.php > 쿠폰 다운*/
	var addPouch = function(_coupon_id){
		var _user_id=sessionStorage.getItem('user_id');
		
		$.ajax({
			type:"post",
			url:ajaxURL+"coupon.php?action=addPouch",
			data:{user_id:_user_id, coupon_id:_coupon_id},
			success:function(result){
				console.log("addPouch");
				console.log(result);
				if(result=="success"){
					alert(SUCCESS_COUPONDOWN_MESSAGE);
					/*몇장남았는지 업데이트 해야지*/
				}else if(result=="fail"){
					alert(FAIL_COUPONDOWN_MESSAGE);
				}else if(result == "no"){
					alert("이미 쿠폰이 있습니다.");
				}
			}
		});
	};
	
	Coupon.ImgError =function(source){
		source.src = "images/default_store.png";
		source.onerror = "";
		return true;
	}
	/*coupon template*/
	var template = {
		couponList : function(result,selector) {
			var info = '';
			info += '<li>';
			info += '<div class="thumbWrap">';
			info += '<a class="store-page-linker" data-store_id='+result.store_id+' href="#">';
			info += '<img src="' + result.image + '" style="width:160px; height:120px;" alt="thumb_store_1">';
			info += '</a>';
			info += '</div>';
			info += '<div class="infoWrap">';
			info += '<h4 class="title">' + result.coupon_title + '</h4>';
			info += '<div class="store"><a class="store-page-linker" data-store_id='+result.store_id+' href="store_view.php?id='+result.store_id+'">' + result.store_name + '</a></div>';
			info += '<div class="tags">'+result.category_name+' <span>|</span> '+result.addr2+'</div>';
			info += '<div class="values">';
			info += '단골 <b>' + result.favoriteCount + '</b>명';
			info += '</div>';
			info += '<div class="date">' + result.expired_date + '</div>';
			info += '</div>';
			info += '<a id="fbShareBtn" class="shareBtn" store_id="'+result.store_id+'" store_name="'+result.store_name+'" coupon_title="'+result.coupon_title+'" coupon_desc="'+result.description+'" coupon_img="'+result.image+'">공유하기</a>';
			info += '<div class="downWrap">';
			info += '<a class="coupon_down" href="#" data-coupon_id ="' + result.coupon_id + ' ">다운로드</a>';
			info += '<div class="cnt"><b>' + (result.total_count-result.count) + '</b>장 남음</div>';
			info += '</div>';
			info += '<div class="clear"></div>';
			info += '</li>';
	
			$(selector).append(info);
		},
		myCouponList : function(result,selector) {
			var info = '';
			info += '<li id="myCoupon" >';
			info += '<div class="thumbWrap">';
			info += '<a class="store-page-linker" data-store_id='+result.store_id+' href="#">';
			info += '<img src="' + result.image + '" style="width:160px; height:120px;" alt="thumb_store_1">';
			info += '</a>';
			info += '</div>';
			info += '<div class="infoWrap">';
			info += '<h4 class="title">' + result.coupon_title + '</h4>';
			info += '<div class="store"><a class="store-page-linker" data-store_id='+result.store_id+' href="store_view.php?id='+result.store_id+'">' + result.store_name + '</a></div>';
			info += '<div class="tags">'+result.category_name+' <span>|</span> '+result.addr2+'</div>';
			info += '<div class="values">';
			info += '단골 <b>' + result.favoriteCount + '</b>명';
			info += '</div>';
			info += '<div class="date">' + result.expired_date + '</div>';
			info += '</div>';
			info += '<div class="sharedownWrap">';			         
			info += '<a id="fbShareBtn" href="#" store_id="'+result.store_id+'" store_name="'+result.store_name+'" coupon_title="'+result.coupon_title+'" coupon_desc="'+result.description+'" coupon_img="'+result.image+'">공유하기</a>';			         	
			info += '<div class="cnt"><span data-coupon_id='+result.coupon_id+'>인쇄하기</span></div></div>';			         
			info += ' <div class="clear"></div>';	
		
			$(selector).append(info);
		},
		noCoupon :function(selector){
			var category_name;
			($('.depth2 .menu .on a').html()=='전체')?category_name=$('.depth1 .menu .on a').html():category_name=$('.depth2 .menu .on a').html().substring(0,$('.depth2 .menu .on a').html().length-3);
		
			var info = '';
			info += '<div class="noneListWrap">';
			info += '<div class="titleArea"><img src="images/nolist_coupon.png" alt=""  />';
			info += '<h4><span>'+sessionStorage.getItem('landmark_name')+'</span>지역의 <span>'+category_name+'</span>카테고리에는 쿠폰이 없습니다.</h4>';
			info += '</div>';
			info += '</div>';	
			
			$(selector).append(info);
		},
		noMyCoupon :function(selector){
			var info = '';
			info += '<div class="noneListWrap">';
			info += '<div class="titleArea"><img src="images/nolist_coupon.png" alt=""  />';
			info += '<h4>발급 받은 쿠폰이 없습니다.</h4>';
			info += '</div>';
			info += '<div class="subArea"><p>다양한 혜택이 있는 쿠폰을 이용해보세요..<br/><br/>';
			info += '<a href="coupon.php"><img src="images/btn_link.png" alt="" /></a></p>';
			info += '</div></div>';	
			
			$(selector).append(info);
		},
		noSideCoupon :function(selector){
			
			var info = '';
			// info += '<h3><img src="images/titles/popular_coupon.png" alt="인기쿠폰"/></h3>';
			// info += '<div class="clear"></div>';
			info += '<li class="first-child">';
			info += '<div class="widgetNoneWrap">';
			info += '<img src="images/nolist_coupon_s.png" alt="nolist_coupon_s"   />';
			info += '<span>쿠폰이 없습니다.</span>';
			info += '</div>';
			info += '</li>';
			
			$(selector).append(info);
		},
		sideCouponList : function(result,selector,key,type){
			var info = '';
			info += '<li '+key+'>';
			info += '<div class="thumbWrap">';
			info += '<a href="#">';
			info += '<img src="' + result.image + '" onerror="Coupon.ImgError(this)" alt="thumb_store_1" />';
			info += '</a></div>';
			info += '<div class="couponFlag"><span>' + result.discount + '%</span></div>';
			info += '<div class="infoWrap">';
			info += '<a class="title" href="store_view.php?id='+result.store_id+'">' + result.store_name + '</a>';
			info += '<div class="desc">' + result.coupon_title + '</div>';
			info += '<div class="downCountWrap">';
			info += '<div class="tags left">'+result.category_name+' <span>|</span> '+result.addr2+'</div>';
			if(type=='popular'){
				info += '<div class="downCount right"><b>'+ parseInt(result.total_count - result.count) + '</b>장 남음</div>';
			}else{
				if(result.isMyPouch==true){
					info += '<div class="downCount right"><a data-coupon_id ="' + result.coupon_id + '" href="#"><img src="images/btn_coupon_s_ok.png" alt></a></div>';	
				}else{
					info += '<div class="downCount right"><a data-coupon_id ="' + result.coupon_id + '" href="#"><img src="images/btn_coupon_s.png" alt></a></div>';
				}
			}
			
			info += '<div class="clear"></div></div></div></li>';
			$(selector).append(info);
		}
	};

})(window);
